package com.cinyi.cyds.base.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.cinyi.cyds.base.bean.Role;
import com.cinyi.cyds.base.bean.SessionInfo;
import com.cinyi.cyds.base.bean.Tree;
import com.cinyi.cyds.base.model.Tresource;
import com.cinyi.cyds.base.model.Trole;
import com.cinyi.cyds.base.model.Tuser;
import com.cinyi.cyds.base.service.RoleServiceI;
import com.cinyi.ormlite.web.dao.DefaultJdbcDaoImpl;

@Service
public class RoleServiceImpl implements RoleServiceI {

	private DefaultJdbcDaoImpl<Trole> roleDao;
	private DefaultJdbcDaoImpl<Tuser> userDao;
	private DefaultJdbcDaoImpl<Tresource> resourceDao;

	public RoleServiceImpl() {
		roleDao = new DefaultJdbcDaoImpl<Trole>();
		userDao = new DefaultJdbcDaoImpl<Tuser>();
		resourceDao = new DefaultJdbcDaoImpl<Tresource>();
	}

	@Override
	public void add(Role role, SessionInfo sessionInfo) throws Exception {
		Trole t = new Trole();
		BeanUtils.copyProperties(role, t);
		if (role.getPid() != null && !role.getPid().equalsIgnoreCase("")) {
			t.setTrole(roleDao.get(role.getPid(), Trole.class));
		}
		roleDao.save(t);

		// 刚刚添加的角色，赋予给当前的用户
		addUserRole(sessionInfo.getId(), t.getId());
	}

	public void addUserRole(String userid, String roleid) throws Exception {
		List<Object> params = new ArrayList<Object>();
		params.add(userid);
		params.add(roleid);
		String user_role_sql = "insert into tuser_trole(tuser_id,trole_id) values(?,?)";
		userDao.executeSQL(user_role_sql, params);
	}

	@Override
	public Role get(String id) throws Exception {
		Role r = new Role();

		Trole t = roleDao.get(id, Trole.class);

		if (t != null) {
			BeanUtils.copyProperties(t, r);
			Trole role = roleDao.get(t.getPid(), Trole.class);
			if (role != null) {
				r.setPid(role.getId());
				r.setPname(role.getName());
			}
			List<Tresource> s = resourceDao
					.findBySQL(
							Tresource.class,
							"select distinct t.ID as id,t.ICON as icon,t.NAME as name,t.REMARK as remark,t.SEQ as seq,t.URL as url,t.PID as pid,t.tresourcetypeId as tresourcetypeId from tresource t where id in(select tresource_id from trole_tresource where trole_id ='"
									+ id + "')");
			if (s != null && !s.isEmpty()) {
				boolean b = false;
				String ids = "";
				String names = "";
				for (Tresource tr : s) {
					if (b) {
						ids += ",";
						names += ",";
					} else {
						b = true;
					}
					ids += tr.getId();
					names += tr.getName();
				}
				r.setResourceIds(ids);
				r.setResourceNames(names);
			}
		}
		return r;
	}

	@Override
	public void edit(Role role) throws Exception {
		Trole t = roleDao.get(role.getId(), Trole.class);
		if (t != null) {
			BeanUtils.copyProperties(role, t);
			if (role.getPid() != null && !role.getPid().equalsIgnoreCase("")) {
				t.setTrole(roleDao.get(role.getPid(), Trole.class));
				t.setPid(role.getPid());
			}
			if (role.getPid() != null && !role.getPid().equalsIgnoreCase("")) {// 说明前台选中了上级资源
				Trole pt = roleDao.get(role.getPid(), Trole.class);
				isChildren(t, pt);// 说明要将当前资源修改到当前资源的子/孙子资源下
				t.setTrole(pt);
				t.setPid(role.getPid());
			} else {
				t.setTrole(null);// 前台没有选中上级资源，所以就置空
				t.setPid(null);
			}
		}
	}

	/**
	 * 判断是否是将当前节点修改到当前节点的子节点
	 * 
	 * @param t
	 *            当前节点
	 * @param pt
	 *            要修改到的节点
	 * @return
	 * @throws Exception
	 */
	private boolean isChildren(Trole t, Trole pt) throws Exception {
		if (pt != null) {
			Trole role = roleDao.get(pt.getPid(), Trole.class);
			if (role != null) {
				if (role.getId().equalsIgnoreCase(t.getId())) {
					pt.setTrole(null);
					pt.setPid(null);
					return true;
				} else {
					return isChildren(t, pt.getTrole());
				}
			}
		}
		return false;
	}

	@Override
	public List<Role> treeGrid(SessionInfo sessionInfo) throws Exception {
		List<Role> rl = new ArrayList<Role>();
		List<Trole> tl = null;
		Map<String, Object> params = new HashMap<String, Object>();
		if (sessionInfo != null) {
			params.put("userId", sessionInfo.getId());// 查自己有权限的角色
			tl = roleDao
					.findBySQL(
							Trole.class,
							"select distinct t.ID as id,t.NAME as name,t.REMARK as remark,t.SEQ as seq,t.PID as pid from trole t where id in(select trole_id from tuser_trole where tuser_id ='"
									+ sessionInfo.getId() + "') order by t.seq");
		} else {
			tl = roleDao.find(new Trole());
		}
		if (tl != null && tl.size() > 0) {
			for (Trole t : tl) {
				Role r = new Role();
				BeanUtils.copyProperties(t, r);
				r.setIconCls("status_online");
				if (t.getPid() != null) {
					Trole role = roleDao.get(t.getPid(), Trole.class);
					if (role != null) {
						r.setPid(role.getId());
						r.setPname(role.getName());
					}
				}
				String resource_sql = "select distinct t.ID as id,t.ICON as icon,t.NAME as name,t.REMARK as remark,t.SEQ as seq,t.URL as url,t.PID as pid,t.tresourcetypeId as tresourcetypeId from tresource t where id in(select tresource_id from trole_tresource where trole_id = '"
						+ t.getId() + "')";
				List<Tresource> s = resourceDao.findBySQL(Tresource.class,
						resource_sql);
				if (s != null && !s.isEmpty()) {
					boolean b = false;
					String ids = "";
					String names = "";
					for (Tresource tr : s) {
						if (b) {
							ids += ",";
							names += ",";
						} else {
							b = true;
						}
						ids += tr.getId();
						names += tr.getName();
					}
					r.setResourceIds(ids);
					r.setResourceNames(names);
				}
				rl.add(r);
			}
		}
		return rl;
	}

	@Override
	public void delete(String id) throws Exception {
		Trole t = roleDao.get(id, Trole.class);
		del(t);
	}

	private void del(Trole t) throws Exception {
		List<Object> params = new ArrayList<Object>();
		params.add(t.getId());
		String role_sql = "select distinct t.ID as id,t.NAME as name,t.REMARK as remark,t.SEQ as seq,t.PID as pid from trole t where t.pid = ?";
		List<Trole> roles = roleDao.findBySQL(Trole.class, role_sql, params);
		if (roles != null && roles.size() > 0) {
			for (Trole r : roles) {
				del(r);
			}
		}
		roleDao.delete(t.getId(), Trole.class);
	}

	@Override
	public List<Tree> tree(SessionInfo sessionInfo) throws Exception {
		List<Trole> l = null;
		List<Tree> lt = new ArrayList<Tree>();

		Map<String, Object> params = new HashMap<String, Object>();
		if (sessionInfo != null) {
			params.put("userId", sessionInfo.getId());// 查自己有权限的角色
			l = roleDao
					.findBySQL(
							Trole.class,
							"select distinct t.ID as id,t.NAME as name,t.REMARK as remark,t.SEQ as seq,t.PID as pid from trole t where id in(select trole_id from tuser_trole where tuser_id ="
									+ sessionInfo.getId() + ") order by t.seq");

		} else {
			l = roleDao.find(new Trole());
		}

		if (l != null && l.size() > 0) {
			for (Trole t : l) {
				Tree tree = new Tree();
				BeanUtils.copyProperties(t, tree);
				tree.setText(t.getName());
				tree.setIconCls("status_online");
				if (t.getTrole() != null) {
					tree.setPid(t.getTrole().getId());
				}
				lt.add(tree);
			}
		}
		return lt;
	}

	@Override
	public List<Tree> allTree() throws Exception {
		return this.tree(null);
	}

	@Override
	public void grant(Role role) throws Exception {
		String delete_sql = "delete from trole_tresource  where trole_id = '"
				+ role.getId() + "'";
		roleDao.executeSQL(delete_sql, null);
		if (role.getResourceIds() != null
				&& !role.getResourceIds().equalsIgnoreCase("")) {
			for (String id : role.getResourceIds().split(",")) {
				List<Object> params = new ArrayList<Object>();
				params.add(role.getId());
				params.add(id);
				String insert_sql = "insert into trole_tresource(trole_id,tresource_id) values(?,?)";
				roleDao.executeSQL(insert_sql, params);
			}
		}
	}

}
